'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/auth-context'
import { 
  Package, 
  Heart, 
  MessageCircle, 
  Star, 
  Upload,
  Calendar,
  Clock,
  ExternalLink
} from 'lucide-react'

interface Activity {
  id: string
  type: 'tool_created' | 'tool_favorited' | 'review_added' | 'tool_updated'
  title: string
  description: string
  targetId: string
  targetTitle: string
  targetUrl?: string
  createdAt: string
  metadata?: {
    rating?: number
    category?: string
    status?: string
  }
}

export function ActivityHistory() {
  const { user } = useAuth()
  const [activities, setActivities] = useState<Activity[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState<'all' | 'tools' | 'favorites' | 'reviews'>('all')

  useEffect(() => {
    if (user) {
      fetchActivities()
    }
  }, [user])

  const fetchActivities = async () => {
    try {
      setLoading(true)
      const response = await fetch('/api/user/activities', {
        headers: {
          'Authorization': 'Bearer dev-user',
          'Content-Type': 'application/json'
        }
      })

      const result = await response.json()
      if (response.ok) {
        setActivities(result.data || [])
      }
    } catch (error) {
      console.error('获取活动历史失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const getActivityIcon = (type: Activity['type']) => {
    switch (type) {
      case 'tool_created':
        return <Upload className="h-4 w-4 text-blue-500" />
      case 'tool_favorited':
        return <Heart className="h-4 w-4 text-red-500" />
      case 'review_added':
        return <MessageCircle className="h-4 w-4 text-green-500" />
      case 'tool_updated':
        return <Package className="h-4 w-4 text-orange-500" />
      default:
        return <Clock className="h-4 w-4 text-gray-500" />
    }
  }

  const getActivityColor = (type: Activity['type']) => {
    switch (type) {
      case 'tool_created':
        return 'bg-blue-50 border-blue-200'
      case 'tool_favorited':
        return 'bg-red-50 border-red-200'
      case 'review_added':
        return 'bg-green-50 border-green-200'
      case 'tool_updated':
        return 'bg-orange-50 border-orange-200'
      default:
        return 'bg-gray-50 border-gray-200'
    }
  }

  const filteredActivities = activities.filter(activity => {
    if (filter === 'all') return true
    if (filter === 'tools') return activity.type === 'tool_created' || activity.type === 'tool_updated'
    if (filter === 'favorites') return activity.type === 'tool_favorited'
    if (filter === 'reviews') return activity.type === 'review_added'
    return true
  })

  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    const now = new Date()
    const diffInHours = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60))

    if (diffInHours < 1) return '刚刚'
    if (diffInHours < 24) return `${diffInHours}小时前`
    if (diffInHours < 24 * 7) return `${Math.floor(diffInHours / 24)}天前`
    return date.toLocaleDateString()
  }

  if (loading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3, 4, 5].map(i => (
          <div key={i} className="animate-pulse">
            <div className="flex space-x-3">
              <div className="h-8 w-8 bg-gray-200 rounded-full"></div>
              <div className="flex-1 space-y-2">
                <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                <div className="h-3 bg-gray-200 rounded w-1/2"></div>
              </div>
            </div>
          </div>
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 筛选器 */}
      <div className="flex space-x-2">
        {[
          { key: 'all', label: '全部', count: activities.length },
          { key: 'tools', label: '工具', count: activities.filter(a => a.type === 'tool_created' || a.type === 'tool_updated').length },
          { key: 'favorites', label: '收藏', count: activities.filter(a => a.type === 'tool_favorited').length },
          { key: 'reviews', label: '评价', count: activities.filter(a => a.type === 'review_added').length }
        ].map(({ key, label, count }) => (
          <button
            key={key}
            onClick={() => setFilter(key as any)}
            className={`px-3 py-1 rounded-full text-sm font-medium transition-colors ${
              filter === key
                ? 'bg-blue-500 text-white'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            {label} ({count})
          </button>
        ))}
      </div>

      {/* 活动列表 */}
      {filteredActivities.length === 0 ? (
        <div className="text-center py-8">
          <Clock className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">暂无活动记录</h3>
          <p className="text-gray-500">
            {filter === 'all' ? '开始使用平台来创建您的第一个活动记录' : '该类型暂无活动记录'}
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {filteredActivities.map((activity) => (
            <div
              key={activity.id}
              className={`border rounded-lg p-4 ${getActivityColor(activity.type)}`}
            >
              <div className="flex items-start space-x-3">
                <div className="flex-shrink-0 mt-1">
                  {getActivityIcon(activity.type)}
                </div>
                
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between">
                    <h4 className="text-sm font-medium text-gray-900">
                      {activity.title}
                    </h4>
                    <span className="text-xs text-gray-500">
                      {formatDate(activity.createdAt)}
                    </span>
                  </div>
                  
                  <p className="text-sm text-gray-600 mt-1">
                    {activity.description}
                  </p>
                  
                  <div className="flex items-center justify-between mt-2">
                    <div className="flex items-center space-x-2">
                      <span className="text-xs font-medium text-gray-700">
                        {activity.targetTitle}
                      </span>
                      
                      {activity.metadata?.rating && (
                        <div className="flex items-center space-x-1">
                          <Star className="h-3 w-3 text-yellow-400 fill-current" />
                          <span className="text-xs text-gray-600">
                            {activity.metadata.rating}
                          </span>
                        </div>
                      )}
                      
                      {activity.metadata?.category && (
                        <span className="text-xs px-2 py-1 bg-white rounded-full text-gray-600">
                          {activity.metadata.category}
                        </span>
                      )}
                      
                      {activity.metadata?.status && (
                        <span className={`text-xs px-2 py-1 rounded-full ${
                          activity.metadata.status === 'APPROVED' 
                            ? 'bg-green-100 text-green-800'
                            : activity.metadata.status === 'PENDING'
                            ? 'bg-yellow-100 text-yellow-800'
                            : 'bg-red-100 text-red-800'
                        }`}>
                          {activity.metadata.status}
                        </span>
                      )}
                    </div>
                    
                    {activity.targetUrl && (
                      <a
                        href={activity.targetUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-xs text-blue-500 hover:text-blue-700 flex items-center space-x-1"
                      >
                        <span>查看</span>
                        <ExternalLink className="h-3 w-3" />
                      </a>
                    )}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
